import axios from 'axios'

import CONFIG from "@/config/shared-config"
import object from "@/utils/object";
import qs from "qs";
import {success,error} from  "@/utils/msg"

const httpFactory = axios.create({
    timeout: CONFIG.REQUEST_TIME_OUT,
    baseURL: CONFIG.SERVER_ADDR,
    withCredentials: false,
})


httpFactory.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'
httpFactory.defaults.crossDomain = true;
httpFactory.defaults.withCredentials = true;  //设置cross跨域 并设置访问权限 允许跨域携带cookie信息

httpFactory.interceptors.request.use(config => {
    config.meta = {startTime: new Date()}; // 为这个请求设置开始时间
    /*CONFIG.SECURITY.TOKEN.EXCLUDE_URL.forEach((url) => {
      if (!config.url.endsWith(url)) {
        //添加认证token
        config.headers[CONFIG.TOKEN_AUTHENTICATION] = securityUtils.getToken();
      }
    });*/
    if (config.Accept == "KV") {
        config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8";
    }
    return config
}, error => {
    console.error(error)
})
httpFactory.interceptors.response.use(response => {
    const headers = response.headers
    if (headers['content-type'] === 'application/octet-stream;charset=utf-8') {
        return response.data
    }
    // data里面的数据要解析，而params里的则不用
    let reqData = response.config.method === 'get' ? response.config.params : response.config.data;
    const resData = response.data;
    if (process.env.NODE_ENV !== 'production' && response.config.url.indexOf("sysDictData/list") == -1) {
        if (typeof reqData === 'string') {
            try {
                if(response.config.Accept == "KV"){
                    reqData = decodeURIComponent(reqData);
                    reqData =  JSON.parse('{"' + reqData.replace(/&/g, '","').replace(/=/g, '":"') + '"}')
                }else{
                    reqData = JSON.parse(reqData)
                }
            } catch (e) {
                qs.parse(reqData);
            }
        }
        console.log('\n')
        const duration = new Date() - response.config.meta.startTime; // 计算请求耗时
        console.group(`${duration}ms -> ` + response.config.method + `: ${response.config.url}`)
        console.log('request: ', reqData)
        console.log('response: ', resData, object.clone(resData.data || null));
        console.groupEnd();
    }
    /* if (response.status === httpResponseStatus.SUCCESS) {
       if (resData.code === httpResponseStatus.SUCCESS) {
         return resData
       }
       switch (resData.code) {
         case httpResponseStatus.RESULT_STATUS_OVERTIME:
           router.push("/login")
           break;
         case httpResponseStatus.UNAUTHORIZED || httpResponseStatus.UNAUTHORIZED:
           router.push("/login")
           break
       }
       return Promise.resolve(resData)
     }*/
    return resData;
}, error => {
    console.error('请求错误', error)
    let {message} = error;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    error(message);
    return Promise.reject({code: 500, data: error})
})


export default httpFactory
